package com.oddpointcc.szpt.accounting.utils;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public final class WebUtil {

	private final static Md5PasswordEncoder MD5_PASSWORD_ENCODER = new Md5PasswordEncoder();

	public static String encoderPassword(String password) {
		return MD5_PASSWORD_ENCODER.encodePassword(password, null);
	}

	public static String getLoginUserUsername() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String username = (String) request.getSession().getAttribute("userUsername");
		return username;
	}

	public static Integer getLoginUserId() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		return userId;
	}

	public static void dowloadFile(HttpServletResponse response, Path path, String originalFilename)
			throws IOException {
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition",
				"attachment; filename=\"" + URLEncoder.encode(originalFilename, "UTF-8") + "\"");
		response.setContentLength((int) Files.size(path));
		Files.copy(path, response.getOutputStream());
		response.flushBuffer();
	}

}
